import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Table, Button, Space, message, Popconfirm, Tree, Card, Input, Form, Modal } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, MenuOutlined } from '@ant-design/icons';
import { history } from 'umi';
import type { DataNode } from 'antd/es/tree';

const { Search } = Input;

const MenuListPage: React.FC = () => {
  const [treeData, setTreeData] = useState<DataNode[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchForm] = Form.useForm();
  const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
  const [selectedMenu, setSelectedMenu] = useState<any>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);

  useEffect(() => {
    fetchMenus();
  }, []);

  const fetchMenus = async (params: any = {}) => {
    setLoading(true);
    try {
      // TODO: Replace with actual API call
      // const response = await fetch('/api/menus', { params });
      // const data = await response.json();
      
      // Mock data for now
      const mockData = [
        {
          id: '1',
          name: '系统管理',
          icon: 'SettingOutlined',
          path: '/system',
          sort: 1,
          status: 1,
          children: [
            {
              id: '2',
              name: '用户管理',
              icon: 'UserOutlined',
              path: '/system/user',
              sort: 1,
              status: 1,
            },
            {
              id: '3',
              name: '角色管理',
              icon: 'TeamOutlined',
              path: '/system/role',
              sort: 2,
              status: 1,
            },
            {
              id: '4',
              name: '菜单管理',
              icon: 'MenuOutlined',
              path: '/system/menu',
              sort: 3,
              status: 1,
            },
            {
              id: '5',
              name: '权限管理',
              icon: 'SafetyCertificateOutlined',
              path: '/system/permission',
              sort: 4,
              status: 1,
            },
          ],
        },
      ];
      
      // Convert to TreeData format
      const convertToTreeData = (menus: any[]): DataNode[] => {
        return menus.map(menu => ({
          key: menu.id,
          title: (
            <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
              <span>
                {menu.icon && <MenuOutlined style={{ marginRight: 8 }} />}
                {menu.name}
              </span>
              <span>{menu.path}</span>
            </div>
          ),
          children: menu.children ? convertToTreeData(menu.children) : [],
          isLeaf: !menu.children || menu.children.length === 0,
          ...menu,
        }));
      };
      
      setTreeData(convertToTreeData(mockData));
    } catch (error) {
      message.error('获取菜单列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = (values: any) => {
    fetchMenus(values);
  };

  const handleReset = () => {
    searchForm.resetFields();
    fetchMenus();
  };

  const handleAdd = () => {
    history.push('/menu/create', { parentId: selectedKeys[0] || '0' });
  };

  const handleEdit = () => {
    if (selectedKeys.length === 0) {
      message.warning('请选择要编辑的菜单');
      return;
    }
    history.push(`/menu/edit/${selectedKeys[0]}`);
  };

  const handleDelete = async () => {
    if (selectedKeys.length === 0) {
      message.warning('请选择要删除的菜单');
      return;
    }
    
    try {
      // TODO: Replace with actual API call
      // await fetch(`/api/menus/${selectedKeys[0]}`, { method: 'DELETE' });
      message.success('删除成功');
      setSelectedKeys([]);
      fetchMenus(searchForm.getFieldsValue());
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSelect = (selectedKeys: React.Key[], info: any) => {
    setSelectedKeys(selectedKeys as string[]);
    setSelectedMenu(info.node);
  };

  const showMenuInfo = () => {
    if (selectedKeys.length === 0) {
      message.warning('请选择一个菜单');
      return;
    }
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <PageContainer
      header={{
        title: '菜单管理',
        breadcrumb: {
          items: [
            { title: '系统管理' },
            { title: '菜单管理' },
          ],
        },
      }}
      extra={[
        <Button 
          key="add" 
          type="primary" 
          icon={<PlusOutlined />} 
          onClick={handleAdd}
          style={{ marginRight: 8 }}
        >
          新建
        </Button>,
        <Button 
          key="edit" 
          icon={<EditOutlined />} 
          onClick={handleEdit}
          style={{ marginRight: 8 }}
        >
          编辑
        </Button>,
        <Popconfirm
          key="delete"
          title="确定要删除选中的菜单吗？"
          onConfirm={handleDelete}
          okText="确定"
          cancelText="取消"
        >
          <Button 
            danger 
            icon={<DeleteOutlined />}
            style={{ marginRight: 8 }}
          >
            删除
          </Button>
        </Popconfirm>,
        <Button 
          key="info" 
          icon={<MenuOutlined />} 
          onClick={showMenuInfo}
        >
          详情
        </Button>,
      ]}
    >
      <Card>
        <Form
          form={searchForm}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 24 }}
        >
          <Form.Item name="name" label="菜单名称">
            <Input placeholder="请输入菜单名称" />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                搜索
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>
        
        <div style={{ background: '#fff', padding: '16px', borderRadius: '4px' }}>
          <Tree
            showLine={{ showLeafIcon: false }}
            showIcon={false}
            defaultExpandAll
            onSelect={handleSelect}
            treeData={treeData}
            selectedKeys={selectedKeys}
            blockNode
          />
        </div>
      </Card>

      <Modal
        title="菜单详情"
        open={isModalVisible}
        onCancel={handleCancel}
        footer={[
          <Button key="close" onClick={handleCancel}>
            关闭
          </Button>,
        ]}
      >
        {selectedMenu && (
          <div>
            <p><strong>菜单名称：</strong>{selectedMenu.name}</p>
            <p><strong>菜单路径：</strong>{selectedMenu.path || '-'}</p>
            <p><strong>图标：</strong>{selectedMenu.icon || '-'}</p>
            <p><strong>排序：</strong>{selectedMenu.sort || '0'}</p>
            <p><strong>状态：</strong>{selectedMenu.status === 1 ? '启用' : '禁用'}</p>
          </div>
        )}
      </Modal>
    </PageContainer>
  );
};

export default MenuListPage;
